/**
 * 信令服务器 相关
 */
var SOCKET = {
    /**
     * websocket对象
     */
    ws: null,
    /**
     * websocket 连接地址
     */
    url: "",
    /**
     * 开始建立连接
     * @returns {boolean}
     */
    start: () => {
        if (typeof (WebSocket) == "undefined") {
            layer.msg('您的浏览器不支持WebSocket', {icon: 5})
            return false;
        }
        var uId = $("#registerDialog input[name='userId']").val();
        if (uId === '' || uId == null) {
            layer.msg('请输入您的用户Id', {icon: 5, time: 1500})
            return false;
        }
        var rId = $("#registerDialog input[name='roomId']").val();
        if (rId === '' || rId == null) {
            layer.msg('请输入房间号', {icon: 5, time: 1500})
            return false;
        }
        var isP = $("#registerDialog input[name='isPub']:checked").val();
        if (isP === '' || isP == null) {
            layer.msg('请选择您的身份', {icon: 5, time: 1500})
            return false;
        }
        roomId = rId;
        userId = uId;
        isPub = isP;

        // 构建 WebSocket URL，使用 localhost
        let protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        let host = window.location.host;  // 使用当前页面的主机和端口
        SOCKET.url = `${protocol}//${host}/signal/`;

        //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
        if (SOCKET.ws != null) {
            SOCKET.ws.close();
            SOCKET.ws = null;
        }
        SOCKET.ws = new WebSocket(SOCKET.url + roomId + '/' + userId + '/'+isPub);
        //打开事件
        SOCKET.ws.onopen = SOCKET.onOpen;
        //关闭事件
        SOCKET.ws.onclose = SOCKET.onClose;
        //发生了错误事件
        SOCKET.ws.onerror = SOCKET.onError;
        // 接收消息
        SOCKET.ws.onmessage = SOCKET.onMessage;
    },
    /**
     * 成功建立
     */
    onOpen: () => {
        layer.closeAll();
        layer.msg('信令服务器连接成功', {icon: 1, time: 1500});
        
        // 发送观众加入通知
        console.log('Sending audience join notification...');
        let params = {
            type: 'notification',
            notificationType: 'audience_join',
            userId: userId,
            roomId: roomId,
            message: `观众 ${userId} 进入了直播间`
        };
        SOCKET.sendMsg(params);

        // 开始建立房间
        setTimeout(async () => {
            if (roomList.length) {
                await RTC.initRoom();
            }
        }, 2000)
    },
    /**
     * 接收服务端推送消息
     */
    onMessage: (msg) => {
        try {
            console.log('Raw message received (audience):', msg);
            let parsedMsg;
            // 检查消息是否已经是对象
            if (typeof msg.data === 'string') {
                parsedMsg = JSON.parse(msg.data);
            } else {
                parsedMsg = msg;
            }
            console.log('Parsed message (audience):', parsedMsg);

            // 聊天消息优先处理
            if (parsedMsg.type === 'chat' && parsedMsg.userId !== userId) {
                console.log('Processing chat message (audience):', parsedMsg);
                OPT.receiveMessage({
                    userId: parsedMsg.userId,
                    message: parsedMsg.message,
                    timestamp: parsedMsg.timestamp
                });
                return;
            }

            // 其他消息处理
            switch (parsedMsg.type) {
                case 'join':
                case 'leave':
                    setTimeout(() => {
                        let params = {"type": "roomUserList", "roomId": roomId}
                        SOCKET.sendMsg(params);
                    }, 1000);
                    break;
                case 'roomUserList':
                    roomList = parsedMsg.data;
                    break;
                case 'call':
                    RTC.onCall(parsedMsg);
                    break;
                case 'offer':
                    RTC.onRemoteOffer(parsedMsg.data.userId, parsedMsg.data.offer);
                    break;
                case 'answer':
                    RTC.onRemoteAnswer(parsedMsg.data.userId, parsedMsg.data.answer);
                    break;
                case 'candidate':
                    RTC.onCandiDate(parsedMsg.data.userId, parsedMsg.data.candidate);
                    break;
            }
        } catch (error) {
            console.error('Error processing message (audience):', error);
        }
    },
    /**
     * 连接发生错误
     */
    onError: () => {
        layer.msg('信令服务器连接失败', {icon: 5, time: 1500})
    },
    /**
     * 连接关闭
     */
    onClose: () => {
        layer.msg('信令服务器已关闭', {icon: 5, time: 1500})
    },
    /**
     * 发送消息
     */
    sendMsg: (obj) => {
        if (SOCKET.ws && SOCKET.ws.readyState === 1) {
            SOCKET.ws.send(JSON.stringify(obj));
        } else {
            layer.msg('请检查连接是否正常？', {icon: 5, time: 1500});
        }
    },
    /**
     * 断开连接
     */
    disConnect: () => {
        if (SOCKET.ws) {
            SOCKET.ws.close();
        }
    }
}